import os
import requests
from PIL import Image
import tempfile
import hmac
from hashlib import sha1
import base64
import uuid
import time
import database


def save_png(image: Image.Image):
    temp_dir = tempfile.mkdtemp()
    name = str(uuid.uuid4())
    file_path = os.path.join(temp_dir, f"liblib_{name}.png")
    image.save(file_path, "PNG")
    return file_path

def make_sign(SecretKey:str,type:str):
    """
    生成签名
    """
    secret_key = SecretKey
    if type == "upload":
        uri = "/api/generate/upload/signature"
    elif type == "generate":
        uri = "/api/generate/comfyui/app"
    elif type == "status":
        uri = "/api/generate/comfy/status"
    elif type == "img2img":
        uri = "/api/generate/webui/img2img"
    else:
        raise ValueError("Invalid type for make_sign")
    timestamp = str(int(time.time() * 1000))
    signature_nonce= str(uuid.uuid4())
    content = '&'.join((uri, timestamp, signature_nonce))
    
    digest = hmac.new(secret_key.encode(), content.encode(), sha1).digest()
    sign = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()
    return sign,timestamp, signature_nonce

def upload_image(AccessKey:str,SecretKey:str,image: Image.Image):
    #1. save image to temp file as png
    p = save_png(image)
    #2  generate OSS upload signature
    now = int(time.time())
    params =  {
     "name" : str(now),
     "extension" : "png"
    } 
    sign, timestamp, signature_nonce = make_sign(SecretKey,"upload")
    postUrl = "https://openapi.liblibai.cloud/api/generate/upload/signature"+f"?AccessKey={AccessKey}&Signature={sign}&SignatureNonce={signature_nonce}&Timestamp={timestamp}"
    response = requests.post(postUrl, json=params)
    result = response.json()
    print("upload signature result:", result)
    
    #3 upload image to OSS
    data = {
    'key': result.get('data').get('key'),
    'policy': result.get('data').get('policy'),
    'x-oss-date': result.get('data').get('xOssDate'),
    'x-oss-expires': result.get('data').get('xOssExpires'),
    'x-oss-signature': result.get('data').get('xOssSignature'),
    'x-oss-credential': result.get('data').get('xOssCredential'),
    'x-oss-signature-version': result.get('data').get('xOssSignatureVersion'),
}

    files = {'file': (str(os.path.basename(p)), open(p, 'rb'), 'image/png')}
    url = result.get('data').get('postUrl')
    response = requests.post(url, data=data, files=files)
    if response.status_code == 204:
        image_url = f"{url}/{result.get('data').get('key')}"
        return image_url
    return None

def get_AccessKey_SecretKey():
    user_id = database.USER_NOW["value"]
    if user_id == 0:
        return None, None
    access_key, secret_key = database.get_user_keys(user_id)
    return access_key, secret_key
